package xyz.qduwo.dao;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import xyz.qduwo.entity.QueryResult;
import xyz.qduwo.entity.UserEntity;
import xyz.qduwo.util.HibernateUtils;

import java.util.List;

public class UserDao {
    /*
     * 保存
     */

    public static void save(UserEntity user) throws RuntimeException{
        Session session = HibernateUtils.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // 开启事务
            session.save(user);
            tx.commit(); // 提交事务
        } catch (RuntimeException e) {
            session.getTransaction().rollback(); // 回滚事务
            throw e;
        } finally {
            session.close(); // 关闭session
        }
    }

    /**
     * 更新
     */
    public static void update(UserEntity user) throws RuntimeException{
        Session session = HibernateUtils.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();

            session.update(user);// 操作

            tx.commit();
        } catch (RuntimeException e) {
            assert tx != null;
            tx.rollback();
            throw e;
        } finally {
            session.close();
        }
    }

    /*
     * 删除
     */
    public static void delete(int id) throws RuntimeException{
        Session session = HibernateUtils.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();

            Object user = session.get(UserEntity.class, id); // 要先获取到这个对象
            session.delete(user); // 删除的是实体对象

            tx.commit();
        } catch (RuntimeException e) {
            assert tx != null;
            tx.rollback();
            throw e;
        } finally {
            session.close();
        }
    }

    /**
     * 根据ID查询一个用户
     * @param id
     * @return
     */
    public static UserEntity getByUserID(int id) throws RuntimeException{
        Session session = HibernateUtils.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            UserEntity user = session.get(UserEntity.class, id); // 要先获取到这个对象
            return user;
        } catch (RuntimeException e) {
            assert tx != null;
            tx.rollback();
            throw e;
        } finally {
            session.close();
        }
    }

    /**
     * 根据用户名返回一个User
     * @param username
     * @return
     */
    public static UserEntity getByUserName(String username) throws RuntimeException{
        Session session = HibernateUtils.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Query query = session.createQuery("FROM UserEntity WHERE username='"+username+"'");
            UserEntity user = (UserEntity) query.uniqueResult();// 操作
            tx.commit();
            return user;
        } catch (RuntimeException e) {
            assert tx != null;
            tx.rollback();
            throw e;
        } finally {
            session.close();
        }
    }

    /*
     * 查询所有
     */
    public static List<UserEntity> findAll() throws RuntimeException{
        Session session = HibernateUtils.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();

            // 方式一：使用HQL语句
            List<UserEntity> list = session.createQuery("FROM UserEntity").list(); // 使用HQL查询

            tx.commit();
            return list;
        } catch (RuntimeException e) {
            assert tx != null;
            tx.rollback();
            throw e;
        } finally {
            session.close();
        }
    }

    /**
     * 分页的查询数据列表
     * @param firstResult 从结果列表中的哪个索引开始取数据
     * @param maxResults 最多取多少条数据
     * @return 一页的数据列表
     */
    @SuppressWarnings("unchecked")
    public static QueryResult findAll(int firstResult, int maxResults) throws RuntimeException{
        Session session = HibernateUtils.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            // 查询一页的数据列表
            // 方式一：
            // Query query = session.createQuery("FROM UserEntity");
            // query.setFirstResult(firstResult);
            // query.setMaxResults(maxResults);
            // List<UserEntity> list = query.list(); // 使用HQL查询

            // 方式二：方法链
            List<UserEntity> list = session.createQuery( //
                    "FROM UserEntity") //
                    .setFirstResult(firstResult) // 
                    .setMaxResults(maxResults) //
                    .list();

            // 查询总记录数
            // session.createQuery("SELECT COUNT(*) FROM UserEntity").list().get(0);
            // Long count = (Long) session.createQuery("SELECT COUNT(*) FROM UserEntity").uniqueResult();
            Long count = (Long) session.createQuery( //
                    "SELECT COUNT(*) FROM UserEntity") //
                    .uniqueResult();
            tx.commit();

            // 返回结果
            return new QueryResult(count.intValue(), list);
        } catch (RuntimeException e) {
            assert tx != null;
            tx.rollback();
            throw e;
        } finally {
            session.close();
        }
    }
}
